<?php
class ProjectFollowersController extends AppController
{
    public $name = 'ProjectFollowers';
    public function beforeFilter()
    {
        if (!Configure::read('Project.is_project_follower_enabled')) {
            throw new NotFoundException(__l('Invalid request'));
        }
        parent::beforeFilter();
    }
    public function index($project_id = null)
    {
        $conditions['ProjectFollower.project_id'] = $project_id;
        $this->pageTitle = __l('Project Followers');
        $this->ProjectFollower->recursive = 1;
        $this->paginate = array(
            'conditions' => $conditions,
            'contain' => array(
                'User' => array(
                    'UserAvatar' => array(
                        'fields' => array(
                            'UserAvatar.id',
                            'UserAvatar.filename',
                            'UserAvatar.dir',
                            'UserAvatar.width',
                            'UserAvatar.height'
                        )
                    ) ,
                    'fields' => array(
                        'username'
                    ) ,
                ) ,
                'Project' => array(
                    'fields' => array(
						'Project.id',
                        'Project.user_id',
						'Project.project_follower_count',
                    )
                )
            ) ,
            'order' => array(
                'ProjectFollower.id' => 'desc'
            )
        );
		if ($this->RequestHandler->prefers('json')) {
			$iphone_project_followers = $this->paginate();
			$iphone_project_follower = array();
			for($i=0;$i<count($iphone_project_followers);$i++)
			{	
				$month = date('F',strtotime($iphone_project_followers[$i]['ProjectFollower']['created']));
				$year = date('Y',strtotime($iphone_project_followers[$i]['ProjectFollower']['created']));
				$date = date('d',strtotime($iphone_project_followers[$i]['ProjectFollower']['created']));
				$created = $month." ".$date;
				
				
				
				$image_options = array(
            			'dimension' => 'iphone_project_thumb',
            			'class' => '',
            			'alt' => 'alt',
            			'title' => 'title',
            			'type' => 'jpg'
        		);
				if(!empty($iphone_project_followers[$i]['User']['UserAvatar']))
				{
				$image_url = Router::url('/', true).$this->ProjectFollower->Project->getImageUrl('UserAvatar', $iphone_project_followers[$i]['User']['UserAvatar'], $image_options);
				}
				else
				{
				$iphone_project_followers[$i]['User']['UserAvatar']['id'] = constant(sprintf('%s::%s', 'ConstAttachment', 'UserAvatar'));
				$image_url = Router::url('/', true).$this->ProjectFollower->Project->getImageUrl('UserAvatar', $iphone_project_followers[$i]['User']['UserAvatar'], $image_options);
				}
				$iphone_project_follower[$i]['Follower_username'] = $iphone_project_followers[$i]['User']['username'];
				$iphone_project_follower[$i]['Follower_user_image'] = $image_url;
				$iphone_project_follower[$i]['Follower_created'] = $created;
			}
			
			$this->view = 'Json';
			$this->set('json',$iphone_project_follower);
		
		}
        $this->set('projectFollowers', $this->paginate());
		if (!empty($this->request->params['named']['type']) and $this->request->params['named']['type'] == 'followers') {
            $this->autoRender = false;
            $this->render('followers_list');
        }
    }
    public function add($project_id = null)
    {
        if (is_null($project_id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $project = $this->ProjectFollower->Project->find('first', array(
            'conditions' => array(
                'Project.id' => $project_id
            ) ,
            'fields' => array(
                'Project.slug',
                'Project.user_id'
            ) ,
            'contain' => array(
                'ProjectFollower' => array(
                    'fields' => array(
                        'ProjectFollower.user_id',
						'ProjectFollower.id'
                    ) ,
                    'conditions' => array(
                        'ProjectFollower.user_id' => $this->Auth->user('id')
                    )
                )
            ) ,
            'recursive' => 1
        ));
        if (!empty($project)) {
         if($project['Project']['user_id'] != $this->Auth->user('id'))
         {
            if (empty($project['ProjectFollower'])) {
                $this->ProjectFollower->create();
                $this->request->data['ProjectFollower']['user_id'] = $this->Auth->user('id');
                $this->request->data['ProjectFollower']['project_id'] = $project_id;
                $this->request->data['ProjectFollower']['action'] = 'add';
                if ($this->ProjectFollower->save($this->request->data)) {
					$response=array(
						'message'=>'Your are successfully following this project',
						'url'=>'project_followers/unfollow/'.$this->ProjectFollower->getLastInsertId(),
						'class'=>'Unfollow',
						'text'=>$this->Auth->user('id')
					);
                    $this->Session->setFlash(__l('Your are successfully following this project') , 'default', null, 'success');
					
                } else {
                    $this->Session->setFlash(__l('Project could not be added as follower. Please, try again') , 'default', null, 'error');
					$response=array(
						'message'=>'Project could not be added as follower',
						'url'=>'project_followers/add/'.$project_id,
						'class'=>'Follow'
					);
                }
            } else {
                $this->Session->setFlash(__l('You have already following this project') , 'default', null, 'error');
				$response=array(
						'message'=>'You have already following this project',
						'url'=>'project_followers/unfollow/'.$project['ProjectFollower'][0]['id'],
						'class'=>'Unfollow'
				);
				
            }
            if ($this->RequestHandler->isAjax() && !$this->RequestHandler->prefers('json')) {
                $this->set('followers_id', $this->ProjectFollower->id);
                $this->render('followers');
            } else if(!$this->RequestHandler->prefers('json')) {
                $this->redirect(array(
                    'controller' => 'projects',
                    'action' => 'view',
                    $project['Project']['slug']
                ));
            }
         }
         else{
            $this->Session->setFlash(__l('You can not follow your own project') , 'default', null, 'error');
			$response=array(
						'message'=>'You can not follow your own project',
						'url'=>'',
						'class'=>''
				);
			if(!$this->RequestHandler->prefers('json'))
			{
            $this->redirect(array(
                    'controller' => 'projects',
                    'action' => 'view',
                    $project['Project']['slug']
                ));
			}
         }
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
		if ($this->RequestHandler->prefers('json')) {

           			 $this->view = 'Json';
           			 $this->set('json', (empty($this->viewVars['iphone_response'])) ? $response : $this->viewVars['iphone_response']);
        }
    }
    public function delete($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $projectFollower = $this->ProjectFollower->find('first', array(
            'conditions' => array(
                'ProjectFollower.id' => $id
            ) ,
            'fields' => array(
                'Project.slug',
                'Project.id'
            ) ,
            'recursive' => 0
        ));
        if (empty($projectFollower)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if ($this->ProjectFollower->delete($id)) {
            $this->Session->setFlash(__l(' You have unfollowed this project') , 'default', null, 'success');
            if ($this->RequestHandler->isAjax()) {
                $this->set('project_id', $projectFollower['Project']['id']);
                $this->render('followers');
            } else if(!$this->RequestHandler->prefers('json')){
                $this->redirect(array(
                    'controller' => 'projects',
                    'action' => 'view',
                    $projectFollower['Project']['slug']
                ));
            }
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
    }
	public function unfollow($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $projectFollower = $this->ProjectFollower->find('first', array(
            'conditions' => array(
                'ProjectFollower.id' => $id
            ) ,
            'fields' => array(
                'Project.slug',
                'Project.id'
            ) ,
            'recursive' => 0
        ));
        if (empty($projectFollower)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if ($this->ProjectFollower->delete($id)) {
            $this->Session->setFlash(__l(' You have unfollowed this project') , 'default', null, 'success');
			$response=array(
					'message'=>'You have unfollowed this project',
					'url'=>'project_followers/add/'.$projectFollower['Project']['id'],
					'class'=>'Follow'
			);
            /*if ($this->RequestHandler->isAjax()) {
                $this->set('project_id', $projectFollower['Project']['id']);
                $this->render('followers');
            } else if(!$this->RequestHandler->prefers('json')){
                $this->redirect(array(
                    'controller' => 'projects',
                    'action' => 'view',
                    $projectFollower['Project']['slug']
                ));
            }*/
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
		if ($this->RequestHandler->prefers('json')) {
           			 $this->view = 'Json';
           			 $this->set('json', (empty($this->viewVars['iphone_response'])) ? $response : $this->viewVars['iphone_response']);
        }
    }
    public function admin_index()
    {
        $this->_redirectGET2Named(array(
            'q'
        ));
        $this->pageTitle = __l('Project Followers');
        $conditions = '';
        $this->ProjectFollower->recursive = 0;
        if (!empty($this->request->params['named']['q'])) {
            $conditions['AND']['OR'][]['Project.name LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $conditions['AND']['OR'][]['User.username LIKE'] = '%' . $this->request->params['named']['q'] . '%';
			$this->request->data['ProjectFollower']['q'] = $this->request->params['named']['q'];
            $this->pageTitle.= sprintf(__l(' - Search - %s') , $this->request->params['named']['q']);
        }
        if (!empty($this->request->params['named']['user_id'])) {
            $conditions['ProjectFollower.user_id'] = $this->request->params['named']['user_id'];
            $project_name = $this->ProjectFollower->User->find('first', array(
                'conditions' => array(
                    'User.id' => $this->request->params['named']['user_id'],
                ) ,
                'fields' => array(
                    'User.username',
                ) ,
                'recursive' => - 1,
            ));
            $this->pageTitle.= sprintf(__l(' - User - %s') , $project_name['User']['username']);
        }
        if (isset($this->request->params['named']['project_id'])) {
            $conditions['ProjectFollower.project_id'] = $this->request->params['named']['project_id'];
            $project_name = $this->ProjectFollower->Project->find('first', array(
                'conditions' => array(
                    'Project.id' => $this->request->params['named']['project_id'],
                ) ,
                'fields' => array(
                    'Project.name',
                ) ,
                'recursive' => - 1,
            ));
            $this->pageTitle.= sprintf(__l(' - %s') , $project_name['Project']['name']);
        }
        $this->paginate = array(
            'conditions' => $conditions,
            'contain' => array(
                'Project' => array(
                    'ProjectStatus',
                ) ,
                'User' => array(
                    'fields' => array(
                        'User.username'
                    )
                ) ,
            ) ,
            'order' => array(
                'ProjectFollower.id' => 'desc'
            )
        );
        $this->set('projectFollowers', $this->paginate());
        $moreActions = $this->ProjectFollower->moreActions;
        $this->set(compact('moreActions'));
    }
    public function admin_delete($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $projectFollower = $this->ProjectFollower->find('first', array(
            'conditions' => array(
                'ProjectFollower.id' => $id
            ) ,
            'fields' => array(
                'Project.slug',
                'Project.id'
            ) ,
            'recursive' => 0
        ));
        if (empty($projectFollower)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        if ($this->ProjectFollower->delete($id)) {
            $this->Session->setFlash(__l(' Project Follower has been deleted') , 'default', null, 'success');
            $this->redirect(array(
                'controller' => 'project_followers',
                'action' => 'index',
            ));
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
    }
    public function admin_update()
    {
        if (!empty($this->request->data[$this->modelClass])) {
            $r = $this->request->data[$this->modelClass]['r'];
            $actionid = $this->request->data[$this->modelClass]['more_action_id'];
            unset($this->request->data[$this->modelClass]['r']);
            unset($this->request->data[$this->modelClass]['more_action_id']);
            $selectedIds = array();
            foreach($this->request->data[$this->modelClass] as $primary_key_id => $is_checked) {
                if ($is_checked['id']) {
                    $selectedIds[] = $primary_key_id;
                }
            }
            if ($actionid && !empty($selectedIds)) {
                if ($actionid == ConstMoreAction::Delete) {
                    $this->{$this->modelClass}->deleteAll(array(
                        $this->modelClass . '.id' => $selectedIds
                    ));
                    $this->Session->setFlash(__l('Checked project follower has been deleted') , 'default', null, 'success');
                }
            }
        }
        $this->redirect(Router::url('/', true) . $r);
    }
}
?>